<!-- eslint-disable vue/valid-v-slot -->
<template>
    <v-layout v-if="isLoading">
        <div style="display: flex;justify-content: center;align-items: center;height: 100vh;width: 100%;">
            <v-progress-circular indeterminate size="50" color="blue" width="1"></v-progress-circular>
        </div>
    </v-layout>
    <v-layout v-else>
        <div style="width: 100%;background-color: rgb(239, 239, 239);padding: 10px;display: flex;">
            <div style="background-color: white;width: 100%;padding: 15px;height: 80vh;">
                <div style="width: 100%;">
                    <div style="display: flex">
                        <el-select size="large" v-model="selected" placeholder="请选择..." @change="getAllScore">
                            <el-option v-for="c in courseNames" :key="c" :value="c">
                                {{ c }}
                            </el-option>
                        </el-select>
                    </div>
                </div>
                <v-divider style="margin-top: 2%;"></v-divider>
                <v-data-table height="65vh" fixed-header :headers="headers" :loading="tableLoading" :items="scores"
                    :sort-by="[{ key: 'regular', order: 'asc' }, { key: 'finalScore', order: 'asc' }]"
                    :no-data-text="selected === '' ? '请选择课程' : '无内容'" items-per-page="-1" hover style="font-size: small;">
                    <template v-slot:top>
                        <v-dialog v-model="isEditing" max-width="500px">
                            <v-card>
                                <v-card-title>
                                    <span class="text-h7">编辑成绩:</span>
                                </v-card-title>

                                <v-card-text>
                                    <v-container>
                                        <v-row>
                                            <v-col cols="6">
                                                <v-text-field v-model="editedItem.number" label="学号" readonly
                                                    variant="plain"></v-text-field>
                                            </v-col>
                                            <v-col cols="6">
                                                <v-text-field v-model="editedItem.studentName" label="姓名" readonly
                                                    variant="plain"></v-text-field>
                                            </v-col>
                                        </v-row>
                                        <v-row>
                                            <v-col cols="6">
                                                <v-text-field v-model="editedItem.regular" label="平时成绩"
                                                    variant="underlined"></v-text-field>
                                            </v-col>
                                            <v-col cols="6">
                                                <v-text-field v-model="editedItem.finalScore" label="期末成绩"
                                                    variant="underlined">
                                                </v-text-field>
                                            </v-col>
                                        </v-row>
                                    </v-container>
                                </v-card-text>

                                <v-card-actions>
                                    <v-spacer></v-spacer>
                                    <v-btn color="blue-darken-1" variant="text" @click="closeDialog">
                                        取消
                                    </v-btn>
                                    <v-btn color="blue-darken-1" variant="text" @click="updateScore()">
                                        保存
                                    </v-btn>
                                </v-card-actions>
                            </v-card>
                        </v-dialog>
                    </template>
                    <template v-slot:item.actions="{ item }">
                        <v-icon size="small" style="cursor: pointer;" @click="editScore(item)">
                            mdi-pencil
                        </v-icon>
                    </template>
                    <template v-slot:bottom>
                        <span style="font-size: small;color: red;">成绩为-1说明未登入成绩,请及时登入!</span>
                    </template>
                </v-data-table>
            </div>
        </div>
    </v-layout>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import type { Course } from '@/models/course';
import { useCourseStore } from '@/stores';
import { GetAllScore, UpdateScore } from '@/controllers/courseController';
import { message } from '@/utils/message';

const headers = [
    { title: '学号', key: 'number', sortable: false },
    { title: '姓名', key: 'studentName', sortable: false },
    { title: '班级', key: 'classNumber', sortable: false },
    { title: '专业', key: 'major', sortable: false },
    { title: '平时成绩', key: 'regular', sortable: true },
    { title: '期末成绩', key: 'finalScore', sortable: true },
    { title: '操作', key: 'actions', sortable: false }
]
let courses = ref([] as Course[])
let courseNames = ref([] as string[])
let selected = ref('')
let isLoading = ref(false)
let tableLoading = ref(false)
let scores = ref([] as {
    userId: number
    number: string
    classNumber: string
    studentName: string
    major: string
    regular: number
    finalScore: number
}[])
let isEditing = ref(false)
let editedItem = ref({
    userId: 0,
    number: '',
    studentName: '',
    regular: 0,
    finalScore: 0
})
onMounted(async () => {
    try {
        isLoading.value = true
        await useCourseStore().init()
        courses.value = useCourseStore().courses.filter((obj, index, array) => {
            return array.findIndex(item => item.id === obj.id) === index;
        })
        courses.value.forEach((c) => {
            courseNames.value.push(c.name)
        })
    }
    catch (err: any) {
        message(err.message, 'error')
    }
    finally {
        isLoading.value = false
    }
})

function getCourseId(name: string) {
    return courses.value.filter(course => course.name === name)[0].id
}

async function getAllScore() {
    if (selected.value === '') return
    tableLoading.value = true
    try {
        scores.value = await GetAllScore(getCourseId(selected.value))
    }
    catch (err: any) {
        message(err.message, 'error')
    }
    finally {
        tableLoading.value = false
    }
}
function editScore(item: any) {
    isEditing.value = !isEditing.value
    editedItem.value.studentName = item.studentName
    editedItem.value.userId = item.userId
    editedItem.value.number = item.number
    if (item.regular !== -1) editedItem.value.regular = item.regular
    if (item.finalScore !== -1) editedItem.value.finalScore = item.finalScore
}
function closeDialog() {
    isEditing.value = !isEditing.value
    editedItem.value.studentName = ''
    editedItem.value.number = ''
    editedItem.value.regular = 0
    editedItem.value.finalScore = 0
}
async function updateScore() {
    if (editedItem.value.regular > 100 || editedItem.value.regular < 0 || editedItem.value.finalScore > 100 || editedItem.value.finalScore < 0) {
        message('成绩超出范围')
        return
    }
    try {
        await UpdateScore(editedItem.value.userId, getCourseId(selected.value), editedItem.value.regular, editedItem.value.finalScore)
        getAllScore().then(closeDialog)
        message('更新成功', 'success')
    }
    catch (err: any) {
        message(err.message, 'error')
    }
}
</script>